//
//  YWWorkTableViewCell.m
//  maintain
//
//  Created by 郑想 on 16/7/28.
//  Copyright © 2016年 ewin. All rights reserved.
//
#import "UIColor+CustomColors.h"
#import "UIImageView+WebCache.h"
#import "UIView+Extension.h"
#import "YWAnimationView.h"
#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWCommonTool.h"
#import "YWEquipmentManager.h"
#import "YWHandler.h"
#import "YWLoginTool.h"
#import "YWMacro.h"
#import "YWMission.h"
#import "YWMissionManager.h"
#import "YWRoundImageView.h"
#import "Masonry.h"
#import "YWWorkTableViewCell.h"
#import "YWDetectAndUpkeepManager.h"
#import "YYLabel.h"
#import "YWContactManager.h"
#import "YWReplyManager.h"
#import "YWReply.h"

@interface YWWorkTableViewCell ()
//头像
@property (nonatomic, strong) UIImageView* pictureImage;
//头像边的时间
@property (nonatomic, strong) YYLabel* littleTimeLable;
//来自 fromPeopleLable
@property (nonatomic, strong) YYLabel* fromPeopleLable;
//编号
@property (nonatomic, strong) YYLabel *numberLabel;
//保养|检测 人
@property (nonatomic, strong) YYLabel *executerManLabel;
//追踪 track
@property (nonatomic, strong) YYLabel *trackLable;
//设备名
@property (nonatomic, strong) YYLabel* deviceNameLabel;
//位置
@property (nonatomic, strong) YYLabel* locationLable;
//任务循环周期
@property (nonatomic, strong) YYLabel* cycleNameLabel;
//已巡查设备
@property (nonatomic, strong) YYLabel* patrolEquipmentLable;
//保养|检测 设备总数
@property (nonatomic, strong) YYLabel* equipmentForInspectionLable;
//截止时间endTimeLable
@property (nonatomic, strong) YYLabel* endTimeLable;
//备注
@property (nonatomic, strong) YYLabel *noteLabel;
//状态图
@property (nonatomic, strong) UIImageView * statusImageview;
@end
@implementation YWWorkTableViewCell
+ (instancetype)cellWithTableView:(UITableView *)tableView
{
    YWWorkTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:YWWorkTableViewCellIdentifier];
    if (cell == nil) {
        cell = [[YWWorkTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:YWWorkTableViewCellIdentifier];
    }
    return cell;
}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.layer.shouldRasterize = YES;
        self.layer.rasterizationScale = [UIScreen mainScreen].scale;
        [self setUpSubviews];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        //self.separatorInset = UIEdgeInsetsMake(0, SCREEN_WIDTH, 0, 0);
    }
    return self;
}

- (void)setMaintenanceMission:(YWMaintenanceMission*)maintenanceMission
{
    _maintenanceMission = maintenanceMission;
    NSString* typeName = [YWCommonTool maintenanceTypeOfMaintenanceTypeId:maintenanceMission.maintenanceTypeId];
    //时间
//    if (maintenanceMission.missionStatus == YWMissionStatusFinished) {
//        _littleTimeLable.text = [YWCommonTool showTimeWithNormalFormatter:maintenanceMission.finishTime / 1000];
//    }else {
        _littleTimeLable.text = [YWCommonTool showTimeWithNormalFormatter:maintenanceMission.createTime / 1000];
//    }
    //    头像
    NSString* downloadUrl = [YWCommonTool pictureDownloadUrl:_maintenanceMission.creator.headIcon];
    [_pictureImage sd_setImageWithURL:[NSURL URLWithString:downloadUrl] placeholderImage:[UIImage imageNamed:@"profile_headimage"]];
    //来自
    self.fromPeopleLable.text = maintenanceMission.creator.userName ? maintenanceMission.creator.userName : NSLocalizedString(@"none", nil);
    //    编号
    _numberLabel.attributedText = [YWCommonTool attributedTextWithFirstText:NSLocalizedString(@"codeFormatter", nil) firstColor:[UIColor customTextGrayBlackColor] secondText:maintenanceMission.missionSequence ?:@"" secondColor:[UIColor customYellowColor] font:kContentFont];
    //执行人
    NSString*executorsName = [YWCommonTool handlerNamesWithHandlers:maintenanceMission.executors];
    _executerManLabel.attributedText = [YWCommonTool attributedTextWithFirstText:[NSString stringWithFormat:@"%@人: ",typeName] firstColor:[UIColor customTextGrayBlackColor] secondText:executorsName secondColor:[UIColor customYellowColor] font:kContentFont];
    //    设备类型名
    NSString*equipmentTypeName = [[YWEquipmentManager shareManager] equipmentTypeNameWithTypeId:maintenanceMission.equipmentTypeId];
    _deviceNameLabel.attributedText = [YWCommonTool attributedTextWithFirstText:NSLocalizedString(@"equipmentFormatter", nil) firstColor:[UIColor customTextGrayBlackColor] secondText:equipmentTypeName secondColor:[UIColor blackColor] font:kContentFont];
    //    位置
    NSString* locationStr= [[YWBuildingManager shareManager] buildingWithId:maintenanceMission.buildingId].buildingName?:@"";
    _locationLable.attributedText = [YWCommonTool attributedTextWithFirstText:NSLocalizedString(@"locationFormatter", nil) firstColor:[UIColor customTextGrayBlackColor] secondText:locationStr secondColor:[UIColor blackColor] font:kContentFont];
    //     任务循环周期
    NSString *cycleString = [YWDetectAndUpkeepManager missionCycleStringWithCycle:maintenanceMission.missionCycle];
    _cycleNameLabel.attributedText = [YWCommonTool attributedTextWithFirstText:NSLocalizedString(@"missionCycleFormatter", nil) firstColor:[UIColor customTextGrayBlackColor] secondText:cycleString?:@"" secondColor:[UIColor blackColor] font:kContentFont];
    //检测设备总数
    _equipmentForInspectionLable.attributedText = [YWCommonTool attributedTextWithFirstText:[NSString stringWithFormat:@"%@%@: ", typeName,NSLocalizedString(@"equipmentCount", nil)] firstColor:[UIColor customTextGrayBlackColor] secondText:[NSString stringWithFormat:@"%ld%@",(long)maintenanceMission.equipmentQuantity,NSLocalizedString(@"ge", nil)] secondColor:[UIColor customYellowColor] font:kContentFont];
    //已检测设备
    _patrolEquipmentLable.attributedText = [YWCommonTool attributedTextWithFirstText:[NSString stringWithFormat:@"已%@%@: ", typeName,NSLocalizedString(@"equipment", nil)] firstColor:[UIColor customTextGrayBlackColor] secondText:[NSString stringWithFormat:@"%ld%@",(long)maintenanceMission.completedQuantity,NSLocalizedString(@"ge", nil)] secondColor:[UIColor customYellowColor] font:kContentFont];
    //进度跟踪
    if ([maintenanceMission.executorIds rangeOfString:[@([YWLoginTool loginUser].uniqueId) stringValue]].location == NSNotFound) {
        _trackLable.text = NSLocalizedString(@"followTheProgress", nil);//@"进度跟踪";
    }
    else {
        _trackLable.text = @"";
    }
    //    截止时间
    NSString*cutoffTime = [YWCommonTool showTime:maintenanceMission.cutoffTime / 1000 andFormatter:KTimeFormatFullDate];
    _endTimeLable.attributedText = [YWCommonTool attributedTextWithFirstText:NSLocalizedString(@"deadlineFormatter", nil) firstColor:[UIColor customTextGrayBlackColor] secondText:cutoffTime secondColor:[UIColor blackColor] font:kContentFont];
    //NSInteger day = [YWCommonTool getDaysFrom:[NSDate date] To:[NSDate dateWithTimeIntervalSince1970:maintenanceMission.cutoffTime / 1000]];
    if (maintenanceMission.status == -1) {
        [_statusImageview setImage:[UIImage imageNamed:@"mission_delete"]];
    }else{
        if (maintenanceMission.missionStatus == YWMissionStatusFinished) {
            [_statusImageview setImage:[UIImage imageNamed:@"mission_newfinished"]];
            //        [self setShowFinishState:YWAnimationViewShowStatusFinished];
        }
        //    else if (day < 0) {
        //        [self setShowFinishState:YWAnimationViewShowStatusExpired];
        //    }
        //    else if (day < kMaxExpireDay) {
        //        [self setShowFinishState:YWAnimationViewShowStatusExpire];
        //    }
        else if(maintenanceMission.missionStatus == YWMissionStatusExpire){
            [_statusImageview setImage:[UIImage imageNamed:@"mission_expire"]];
            //        [self setShowFinishState:YWAnimationViewShowStatusUnfinish];
        }else{
            [_statusImageview setImage:nil];
        }   
    }
    //状态图类型
//    _statusImageview.type = YWAnimationViewTypeRectangle;
    //备注
    NSString *noteText = maintenanceMission.note.length ?maintenanceMission.note: NSLocalizedString(@"none", nil);
    _noteLabel.attributedText = [YWCommonTool attributedTextWithFirstText:NSLocalizedString(@"noteFormatter", nil) firstColor:[UIColor customTextGrayBlackColor] secondText:noteText secondColor:[UIColor blackColor] font:kContentFont];
    
    //任务参与人，要把报障人算进去
    NSMutableArray *tempArray = [NSMutableArray array];
    NSMutableArray *observerArray = [NSMutableArray array];
    [tempArray addObject:maintenanceMission.creator];
    [tempArray addObjectsFromArray:maintenanceMission.executors];
    [tempArray addObjectsFromArray:maintenanceMission.observers];
    for (YWHandler *handler in tempArray) {
        NSInteger uniqueId = handler.uniqueId;
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"uniqueId", uniqueId];
        NSArray *array = [[observerArray filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count==0) {
            [observerArray addObject:handler];
        }
    }
    NSString * firstStr = [NSString stringWithFormat:@"参与人(%ld): ",(long)observerArray.count];
    NSMutableString *observerName = [[NSMutableString alloc] init];
    [observerArray enumerateObjectsUsingBlock:^(YWHandler*  _Nonnull handler, NSUInteger idx, BOOL * _Nonnull stop) {
        if (observerName.length && idx!=0) {
            [observerName appendString:@" "];
        }
        [observerName appendString:handler.userName];
    }];
    
    NSString * nameStr = [NSString stringWithFormat:@"%@",observerName?:@""];//参与者要加进来
    
    self.observersLabel.attributedText = [YWCommonTool attributedTextWithFirstText:firstStr firstColor:[UIColor customTextGrayBlackColor] secondText:nameStr secondColor:[UIColor customBlueColor] font:kContentFont];
    //有评论
    NSArray *commentArray = [[YWReplyManager alloc] replysWithtRelationId:maintenanceMission.missionId andRelationType:YWReplyRelationTypeDetectAndUpkeep];
    if (commentArray.count>0) {
        YWReply * reply = [commentArray firstObject];
        NSString * replyCount = [NSString stringWithFormat:@"评论(%ld): ",commentArray.count];
        //    时间
        NSString * timeStr = [YWCommonTool recordDateByFormatTimeString:reply.replyTime/1000 showYear:YES];
        NSString * timeText = [NSString stringWithFormat:@"  %@",timeStr];
        //    内容
        NSString *replyName = [NSString stringWithFormat:@"%@: ",reply.replier.userName];
        NSString *atUserName = reply.atUser.userName.length>0?[NSString stringWithFormat:@" @%@",reply.atUser.userName]:@"";
        NSString * content = atUserName.length?[NSString stringWithFormat:@" %@  ",reply.content.length>0?reply.content:@""] : (reply.content.length>0?reply.content:@"");
        
        self.replyLabel.attributedText = [YWCommonTool attributedTextWithFirstText:replyCount firstColor:[UIColor customTextGrayColor] firstFont:kContentFont secondText:replyName secondColor:[UIColor customBlueColor] secFont:kContentFont thirdText:atUserName thirdColor:[UIColor customBlueColor] thirdFont:kContentFont fourthText:content fourthColor:[UIColor blackColor] fourFont:kContentFont fifthText:timeText fifthColor:[UIColor customTextGrayColor] fifthFont:[UIFont systemFontOfSize:13]];
    }else{
        self.replyLabel.attributedText = nil;
    }
    
    self.noteLabel.preferredMaxLayoutWidth = self.noteLabel.frame.size.width;
    self.executerManLabel.preferredMaxLayoutWidth = self.executerManLabel.frame.size.width;
    self.deviceNameLabel.preferredMaxLayoutWidth = self.deviceNameLabel.frame.size.width;
    self.locationLable.preferredMaxLayoutWidth = self.locationLable.frame.size.width;
    self.cycleNameLabel.preferredMaxLayoutWidth = self.cycleNameLabel.frame.size.width;
    self.observersLabel.preferredMaxLayoutWidth = self.observersLabel.frame.size.width;
    self.replyLabel.preferredMaxLayoutWidth = self.replyLabel.frame.size.width;

}

//- (void)setShowFinishState:(YWAnimationViewShowStatus)animationViewShowStatus
//{
//    self.statusImageview.showStatus = animationViewShowStatus;
//}

- (void)setUpSubviews {
    UIView *superview = self.contentView;
    /**
     *  头像 名字
     *  头像 时间
     */
    [self.pictureImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.top.mas_equalTo(superview).offset(8);
        make.width.and.height.mas_equalTo(@46);
    }];
    
    [self.fromPeopleLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(_pictureImage.mas_centerY).offset(-2);
        make.left.mas_equalTo(_pictureImage.mas_right).offset(6);
    }];
    
    [self.littleTimeLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_fromPeopleLable);
        make.top.mas_equalTo(_fromPeopleLable.mas_bottom).offset(4);
    }];
    /**
     *  编号
     *  检测人  进度追踪
     *  设备
     *  位置
     *  任务循环周期
     *  检测设备总数  已检测设备
     *  截止时间
     *  备注
     */
    
    [self.numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_pictureImage.mas_bottom).offset(6);
        make.left.mas_equalTo(superview).offset(8);
        make.right.mas_equalTo(superview).offset(-8);
    }];
    
    [self.executerManLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_numberLabel.mas_bottom).offset(6);
        make.left.mas_equalTo(superview).offset(8);
        make.right.mas_equalTo(superview).offset(-72);
    }];
    
    [self.trackLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_numberLabel);
        make.width.mas_equalTo(@64);
        make.right.mas_equalTo(superview).offset(-8);
    }];
    
    [self.deviceNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_executerManLabel.mas_bottom).offset(6);
        make.left.mas_equalTo(superview).offset(8);
        make.right.mas_equalTo(superview).offset(-72);
    }];
    
    [self.locationLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_deviceNameLabel.mas_bottom).offset(6);
        make.left.mas_equalTo(superview).offset(8);
        make.right.mas_equalTo(superview).offset(-72);
    }];
    
    [self.cycleNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_locationLable.mas_bottom).offset(6);
    }];
    
    [self.equipmentForInspectionLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_cycleNameLabel.mas_bottom).offset(6);
        make.left.mas_equalTo(_numberLabel);
        make.right.mas_equalTo(superview.mas_centerX).offset(10);
    }];
    
    [self.patrolEquipmentLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.baseline.mas_equalTo(_equipmentForInspectionLable);
        make.left.mas_equalTo(superview.mas_centerX).offset(15);
    }];
    
    [self.endTimeLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_equipmentForInspectionLable.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(@[_numberLabel,_cycleNameLabel]);
    }];
    
    
    [self.noteLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_endTimeLable.mas_bottom).offset(6);
        make.left.mas_equalTo(_numberLabel);
        make.right.mas_equalTo(superview).offset(-8);
//        make.bottom.mas_equalTo(superview.mas_bottom).offset(-5);
    }];
    
    [self.separatorLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_noteLabel.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(superview);
        make.height.mas_equalTo(@1.0);
    }];
    
    [self.observersLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.separatorLineView.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(_numberLabel);
    }];
    [self.replyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.observersLabel.mas_bottom).offset(6);
        make.left.and.right.mas_equalTo(_numberLabel);
        make.bottom.mas_equalTo(superview).offset(-6);
    }];
    
    [self.statusImageview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_executerManLabel);
        make.right.mas_equalTo(superview).offset(-8);
        make.size.mas_equalTo(CGSizeMake(64, 64));
//        make.size.mas_equalTo(CGSizeMake(70, 20));
//        make.right.and.bottom.mas_equalTo(superview);
    }];
}

//- (void)layoutSubviews{
//    [super layoutSubviews];
//    
//}

- (UIImageView *)pictureImage{
    if (!_pictureImage) {
        UIImageView *imageView = [UIImageView new];
        imageView.clipsToBounds = YES;
        imageView.layer.cornerRadius = 46/2;
        _pictureImage = imageView;
        [self.contentView addSubview:_pictureImage];
    }
    return _pictureImage;
}

- (YYLabel *)fromPeopleLable{
    if (!_fromPeopleLable) {
        YYLabel *label = [[YYLabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor blackColor];
        _fromPeopleLable = label;
        [self.contentView addSubview:_fromPeopleLable];
    }
    return _fromPeopleLable;
}

- (YYLabel *)littleTimeLable{
    if (!_littleTimeLable) {
        YYLabel *label = [[YYLabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor customTextGrayBlackColor];
        _littleTimeLable = label;
        [self.contentView addSubview:_littleTimeLable];
    }
    return _littleTimeLable;
}

- (YYLabel *)numberLabel{
    if (!_numberLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        _numberLabel = label;
        [self.contentView addSubview:_numberLabel];
    }
    return _numberLabel;
}

- (YYLabel *)executerManLabel{
    if (!_executerManLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        label.numberOfLines = 0;
        _executerManLabel = label;
        [self.contentView addSubview:_executerManLabel];
    }
    return _executerManLabel;
}

- (YYLabel *)trackLable{
    if (!_trackLable) {
        YYLabel *label = [[YYLabel alloc] init];
        label.font = kContentFont;
        label.textColor = [UIColor customBlueColor];
        _trackLable = label;
        [self.contentView addSubview:_trackLable];
    }
    return _trackLable;
}

- (YYLabel *)deviceNameLabel{
    if (!_deviceNameLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        label.numberOfLines = 0;
        _deviceNameLabel = label;
        [self.contentView addSubview:_deviceNameLabel];
    }
    return _deviceNameLabel;
}

- (YYLabel *)locationLable{
    if (!_locationLable) {
        YYLabel *label = [[YYLabel alloc] init];
        label.numberOfLines = 0;
        _locationLable = label;
        [self.contentView addSubview:_locationLable];
    }
    return _locationLable;
}

- (YYLabel *)cycleNameLabel{
    if (!_cycleNameLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        label.numberOfLines = 0;
        _cycleNameLabel = label;
        [self.contentView addSubview:_cycleNameLabel];
    }
    return _cycleNameLabel;
}


- (YYLabel *)equipmentForInspectionLable{
    if (!_equipmentForInspectionLable) {
        YYLabel *label = [[YYLabel alloc] init];
        _equipmentForInspectionLable = label;
        [self.contentView addSubview:_equipmentForInspectionLable];
    }
    return _equipmentForInspectionLable;
}

- (YYLabel *)patrolEquipmentLable{
    if (!_patrolEquipmentLable) {
        YYLabel *label = [[YYLabel alloc] init];
        _patrolEquipmentLable = label;
        [self.contentView addSubview:_patrolEquipmentLable];
    }
    return _patrolEquipmentLable;
}

- (YYLabel *)endTimeLable{
    if (!_endTimeLable) {
        YYLabel *label = [[YYLabel alloc] init];
        _endTimeLable = label;
        [self.contentView addSubview:_endTimeLable];
    }
    return _endTimeLable;
}

- (YYLabel *)noteLabel{
    if (!_noteLabel) {
        YYLabel *label = [[YYLabel alloc] init];
        label.numberOfLines = 0;
        _noteLabel = label;
        [self.contentView addSubview:_noteLabel];
    }
    return _noteLabel;
}

//-(YWAnimationView *)statusImageview{
//    if (!_statusImageview) {
//        YWAnimationView *imageView = [YWAnimationView new];
//        _statusImageview = imageView;
//        [self.contentView addSubview:_statusImageview];
//    }
//    return _statusImageview;
//}
- (UIImageView*)statusImageview{
    if (!_statusImageview) {
        UIImageView *imageView = [UIImageView new];
        imageView.layer.masksToBounds = YES;
        imageView.layer.cornerRadius = 32;
        _statusImageview = imageView;
        [self.contentView addSubview:_statusImageview];
    }
    return _statusImageview;
}

@end
